import {
	AppServices
} from "@/services";
import config from "@/config/index.js";
import utils from "@/common/utils/utils.js";

// 前台上传图片接口
function uploadImg(callback) {
	uni.chooseImage({
		count: 1, //默认9
		sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ["album", "camera"], //从相册选择
		async success(res) {
			//console.log(11111111111,res, config.imgUrl);
			uni.showLoading({
			  title: "上传中",
			  mask: true,
			});
			//console.log(11111111111,config.imgUrl + "/Login/Img_up");
			uni.uploadFile({
				// 需要上传的地址
				url: config.imgUrl + "/Login/Img_up",
				// filePath  需要上传的文件
				filePath: res.tempFilePaths[0],
				name: "file",
				header: {
					"Content-Type": "multipart/form-data",
					'accept': 'application/json'
				},
				success(res1) {
					// 显示上传信息
					//console.log(res1)
					const data = JSON.parse(res1.data);
					let code = data.code;
					let message = data.msg;
					//统一处理返回值
					switch (Number(code)) {
						case 200:
							callback(data.data);
							break;
						case 9999:
							utils.toast("您的账号已离线，请重新登录");
							uni.
							setTimeout(() => {
								uni.reLaunch({
									url: "/pages/login/index",
								});
							}, 1500);
							break;
						default:
							utils.toast(`${message}`);
							break;
					}
				},
				complete: () => {
					uni.hideLoading();
				},
				fail: (error)=>{
					//console.log(error)
				}
			});
		},
	});
}
// 请求成功处理函数
const successHandler = async (res, isUpload) => {
  // console.log(res, '请求成功返回的数据')
  let result = true
  let data = null
  const { statusCode: status } = res
  if (status === 200) {
    let resData = res.data
    if (isUpload) {
      try {
        resData = JSON.parse(resData)
        data = resData.data
      } catch (e) {
        await console.log('上传失败')
        result = false
        data = res.msg
      }
    } else if (resData.code === 200) {
      data = resData.data
    } else {
      await console.log(
        resData.msg,
        '请求报错，查下代码-------------------------------'
      )
      // 取消提示
      // await wx.showToast({
      //   title: resData.msg,
      //   icon: "none",
      //   duration: 2000,
      // })
      result = false
      data = res.msg
    }
  } else {
    let message = '未知错误'
    if (status === 401) {
      message = 'Token过期，请重新登录' // 401: Token过期，请重新登录
      // clearTokenAndLogin()
    }
    if (status === 404) {
      message = '404: 请求地址不存在'
    }
    if (status === 405) {
      message = '405: 请求方式不支持'
    }
    if (status === 500) {
      message = '500: 服务器内部错误'
    }
    if (message) await console.log(message, '发生了甚么事？？？')
    result = false
    data = message
  }
  return {
    result,
    data
  }
}
export const uploadFile = ({ name = 'file', filePath, formData }) => {
  return new Promise((resolve, reject) => {
    console.log(filePath)
    wx.uploadFile({
      url: 'https://hsy.sunsetbetter.com/live-hub/api/third/v1/cos/uploadFile', // 文件存放地址
      name,
      filePath,
      formData,
      success: async res => {
        console.log('文件上传成功：', res)
        const { result, data } = await successHandler(res, true)
        console.log(result, data, '上传文件处理后')
        result ? resolve(data) : reject(data)
      },
      fail: err => {
        console.log(err, 'upload fail')
      }
    })
  })
}
module.exports = {
	uploadImg,
	uploadFile
};
